<?php
/**
 * abstract_factory.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2018/09/08
 * Time: 10:21
 */
interface Shape {
    public function draw();
}

class Rectangle implements Shape {
    #Override
    public function draw()
    {
        // TODO: Implement draw() method.
        echo("Inside Rectangle::draw() method.\n");
    }
}
class Square implements Shape {
    #Override
    public function draw()
    {
        // TODO: Implement draw() method.
        echo("Inside Square::draw() method.\n");
    }
}
class Circle implements Shape {
    #Override
    public function draw()
    {
        // TODO: Implement draw() method.
        echo("Inside Circle::draw() method.\n");
    }
}

interface Color {
    public function fill();
}

class Red implements Color {
    #Override
    public function fill()
    {
        // TODO: Implement draw() method.
        echo("Inside Red::fill() method.\n");
    }
}
class Green implements Color {
    #Override
    public function fill()
    {
        // TODO: Implement draw() method.
        echo("Inside Green::fill() method.\n");
    }
}
class Blue implements Color {
    #Override
    public function fill()
    {
        // TODO: Implement draw() method.
        echo("Inside Blue::fill() method.\n");
    }
}

/**
 * 为 Color 和 Shape 对象创建抽象类来获取工厂
 */
abstract class AbstractFactory {
    abstract public function getColor($color);
    abstract public function getShape($shape);
}

/**
 * 创建扩展了 AbstractFactory 的工厂类，基于给定的信息生成实体类的对象
 */
class ShapeFactory extends AbstractFactory {
    public function getColor($color){
        return null;
    }
    public function getShape($shape){
        return new $shape();
    }
}
class ColorFactory extends AbstractFactory {
    public function getColor($color){
        return new $color;
    }
    public function getShape($shape){
        return null;
    }
}

/**
 * 创建一个工厂创造器/生成器类，通过传递形状或颜色信息来获取工厂
 */
class FactoryProducer {
    public function getFactory($choice){
        return new $choice();
    }
}

$factoryProducer = new FactoryProducer;
$shapeFactory = $factoryProducer->getFactory('ShapeFactory');
$shapeFactory->getShape('Rectangle')->draw();
$shapeFactory->getShape('Square')->draw();
$shapeFactory->getShape('Circle')->draw();
$colorFactory = $factoryProducer->getFactory('ColorFactory');
$colorFactory->getColor('Red')->fill();
$colorFactory->getColor('Green')->fill();
$colorFactory->getColor('Blue')->fill();

//file_put_contents('a.log',serialize($shapeFactory));
$a = unserialize(file_get_contents('a.log'));
$a->getShape('Rectangle')->draw();
$a->getShape('Square')->draw();
$a->getShape('Circle')->draw();